import React, { useEffect, useState } from "react";
import { Modal, message, Dropdown, Tooltip, Space } from "antd";
import { hiprint } from "vue-plugin-hiprint";
import PrintModal from "./component/PrintModal";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import SelectActions from "@/views/components/SelectActions";
import PurchaseOrderDetailModal from "./component/PurchaseOrderDetailModal";
import ForceCompletionModal from "./component/ForceCompletionModal";
import SetIncomingWarehouseModal from "./component/SetIncomingWarehouseModal";
import useColumns from "./cloumns";
import { getPurchaseorderList } from "./service";
import { hiprintTipsModal } from "@/utils/utils.jsx";
import { useSearchParams, useLocation } from "react-router-dom";
const PurchaseOrder = () => {
	const [visible, setVisible] = useState("");
	const [printParams, setPrintParams] = useState({});
	const [printType, setPrintType] = useState({});
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);
	const [recordItem, setRecordItem] = useState({}); //每行数据
	const [filteredArray, setFilteredArray] = useState([]); // 拿货员列表
	const [takeGoods, setTakeGoods] = useState(null);

	const handleTakeGoodsChange = value => {
		setTakeGoods(value);
	};
	const { defaultColumns } = useColumns({
		handleDetailVisible,
		handleTakeGoodsChange,
		takeGoods,
		selectedWarehouse,
		handleWarehouseChange
	});
	const tableRequest = getPurchaseorderList;

	const [columns, setColumns] = useState(defaultColumns);
	const beforeQuerySearch = ({ API_DATA }) => {
		const KEYS = ["purchaseOrderNos"];
		// 逗号分割转换数组
		KEYS.forEach(key => {
			API_DATA[key] = API_DATA[key]?.split(",");
		});
		if (!API_DATA.dateType) {
			API_DATA.dateType = 1;
		}
		return API_DATA;
	};
	const tableKey = "GoodsWarehouseOrder312";
	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		columns,
		tableRequest,
		autoFetch: true,
		hasPagination: true,
		hasQuickSearch: true,
		beforeQuerySearch,
		resetSourceData: false,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true
	});
	const commonHandleClick = (status, record) => {
		// 打印采购标签
		if (selectedRows.length > 0 || record) {
			if (status == "print") {
				setPrintType(2);
				if (!hiprint.hiwebSocket.opened) {
					return hiprintTipsModal();
				}
				if (!selectedRows.length) {
					return message.info("请选择需要打印的商品");
				}
				const filteredArray = selectedRows.filter(item => item.payStatus !== 1);
				if (filteredArray.length > 0) {
					setPrintParams(selectedRows);
					setVisible(status);
				} else {
					return message.info("没有可操作的数据，请重新勾选");
				}
			} else if (status == "PasseExamine") {
				// 审核通过
				const filteredArray = selectedRows.filter(item => item.status == "wait-audit");
				if (filteredArray.length > 0) {
					setFilteredArray(filteredArray);
					setVisible(status);
				} else {
					return message.info("没有可操作的数据，请重新勾选");
				}
			} else if (status == "SetIncomingWarehouseModal" || status == "Cancellation") {
				// 作废、指派
				const filteredArray = selectedRows.filter(item => item.status == "wait-audit" || item.status == "wait-pickup");
				if (filteredArray.length > 0) {
					setVisible(status);
					setFilteredArray(filteredArray);
				} else {
					return message.info("没有可操作的数据，请重新勾选");
				}
			} else if (status == "ForceCompletionModal") {
				// 强制完成
				const filteredArray = selectedRows.filter(item => item.status == "partial-pickup");
				if (filteredArray.length > 0) {
					setVisible(status);
					setFilteredArray(filteredArray);
				} else {
					return message.info("没有可操作的数据，请重新勾选");
				}
			} else {
				setVisible(status);
			}
		} else {
			Modal.info({ centered: true, content: "没有可操作的数据，请重新勾选" });
		}
	};
	async function handleWarehouseChange(value, record) {
		setSelectedWarehouse(value);
		message.success("修改成功");
	}
	async function handleDetailVisible(record) {
		setRecordItem(record);
		setVisible("PurchaseOrderDetailModal");
	}

	const [searchParams] = useSearchParams();
	const location = useLocation();

	useEffect(() => {
		const purchaseOrderNos = searchParams.get("purchaseOrderNos");
		if (location.pathname == "/views/purchase/PurchaseOrder") {
			const searchQuery = purchaseOrderNos ? { purchaseOrderNos } : { purchaseOrderNos: "" };
			form.setFieldsValue(searchQuery);
			updateSearchQuery(searchQuery);
			fetchList(searchQuery);
		}
	}, [location.pathname]);

	const CheckPurchaseOrderProps = {
		visible,
		query,
		fetchList,
		checkedRows: selectedRows,
		dataSource,
		filteredArray,
		recordItem,
		checkedIds: selectedKeys,
		handleOk() {
			updateTableList(selectedRows);
		},
		handleCancel() {
			setVisible("");
		}
	};

	const PrintModalProps = {
		visible: visible,
		printType,
		dataSource,
		recordItem,
		selectedRows,
		printParams,
		selectedKeys,
		handleCancel() {
			setVisible("");
			setRecordItem({});
		},
		handleOk(val) {
			setVisible("");
			setRecordItem({});
		}
	};

	const LeftBtns = (
		<Space>
			<SelectActions name="审核通过" onClick={() => commonHandleClick("PasseExamine")} />
			<SelectActions name="作废" onClick={() => commonHandleClick("Cancellation")} />
			<SelectActions name="强制完成" onClick={() => commonHandleClick("ForceCompletionModal")} />
			<SelectActions name="重新指派" onClick={() => commonHandleClick("SetIncomingWarehouseModal")} />
			<SelectActions name="打印采购标签" onClick={() => commonHandleClick("print")} />
		</Space>
	);

	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={LeftBtns} mounted={false} {...searchSimpleTableProps} />
			{(visible == "ForceCompletionModal" || visible == "Cancellation" || visible == "PasseExamine") && (
				<ForceCompletionModal {...CheckPurchaseOrderProps} />
			)}
			{visible == "PurchaseOrderDetailModal" && <PurchaseOrderDetailModal {...CheckPurchaseOrderProps} />}
			{visible == "SetIncomingWarehouseModal" && <SetIncomingWarehouseModal {...CheckPurchaseOrderProps} />}
			{visible == "print" && <PrintModal {...PrintModalProps} />}
		</>
	);
};

export default React.memo(PurchaseOrder, () => {
	return true;
});
